<?php
/**
 * 购买产生返点脚本生成
 * 是7天后给
 */
require_once(dirname(__FILE__)."/../config/include.php");
	
$GLOBALS['DEBUG_SQL_LOG'] = true ;


sql_connect() ;


function log_save_rebate($logs)
{
	$time = date("Ymd H:i:s") ;
	$save_log_filename = dirname(__FILE__)."/log_core_pay_rebate.txt" ;
	file_put_contents($save_log_filename,"$time -- $logs .\r\n",FILE_APPEND);
}
function get_user_string_rebate($pay_userinfo , $fd_userinfo)
{
	$allmemo = "" ;
	if (is_null($pay_userinfo) == false && is_array($pay_userinfo) == true){
		$allmemo .= " : 付款用户:uid = " . $pay_userinfo['id'] . " , name = " . $pay_userinfo['username'] . " , type = " . $pay_userinfo['user_type'] ;
	}
	if (is_null($fd_userinfo) == false && is_array($fd_userinfo) == true){
		$allmemo .= " : 返点用户:uid = " . $fd_userinfo['id'] . " , name = " . $fd_userinfo['username'] . " , type = " . $fd_userinfo['user_type'] ;
	}
	return $allmemo ;
}
function err_insert_rebate($pay_uid , $trade_no , $all_money , $pay_userinfo , $fd_userinfo ,$memo)
{
	$allmemo = $memo . get_user_string_rebate($pay_userinfo , $fd_userinfo);
	 
	sql_query("INSERT INTO `pay_trade_rebate` " .
			"(`uid`, `trade_no`, `money`, `rebate_money`, `level`, `rebate_uid`, " .
			"`rebate_rate`, `state`, `create_time`, `memo`) " .
		"VALUES ('0', '$trade_no', '$all_money', '0', '0', '$pay_uid'," .
				" '0', '2', unix_timestamp(), '$allmemo')") ;
	

	log_save_rebate("$trade_no  :  $allmemo") ;
}
function ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $pay_userinfo , $fd_userinfo ,$memo , $level)
{
	$allmemo = $memo . get_user_string_rebate($pay_userinfo , $fd_userinfo);

	$fd_uid = $fd_userinfo['id'] ;
	$rebate_money = $all_money * $rate / 100 ;
	sql_query("INSERT INTO `pay_trade_rebate` " .
			"(`uid`, `trade_no`, `money`, `rebate_money`, `level`, `rebate_uid`, " .
			"`rebate_rate`, `state`, `create_time`, `memo`) " .
		"VALUES ('$fd_uid', '$trade_no', '$all_money', '$rebate_money', '$level', '$pay_uid'," .
			" '$rate', '0', unix_timestamp(), '$allmemo')") ;
	
	log_save_rebate("$trade_no  :  $allmemo") ;
}

function invite_back_pay($user_invite , $pay_uid , $trade_no , $all_money , $level)
{
	$invite_f = $user_invite['invite_f'] ;
	$invite_m = $user_invite['invite'] ;
	$user_state = $user_invite['user_type'] ;
	
	if($invite_f == "888888" || $invite_m == "888888")	{
		err_insert_rebate($pay_uid , $trade_no , $all_money , $user_invite , null ,"邀请码为888888不产生返点") ;
	}elseif ($user_state == 1 || $user_state == 2 || $user_state == 3){
		if ($level == 1){
			invite_back_pay_one($invite_f , $user_invite , $pay_uid , $trade_no , $all_money) ;
		}elseif ($level == 2){
			invite_back_pay_two($invite_f , $user_invite , $pay_uid , $trade_no , $all_money) ;
		}
	}else{
		err_insert_rebate($pay_uid , $trade_no , $all_money , $user_invite , null ,"此用户类型没有返点：state=".$user_state) ;
	}
}

function invite_back_pay_one($invite_f , $user_invite , $pay_uid , $trade_no , $all_money )
{
	// 付款用户的第一个上级用户
	$userone =  sql_fetch_one("select * from `user_info` where `id` = (select `uid` from `user_invite` where `invite` = '$invite_f')") ;
	if (is_array($userone))
	{
		$uid_one = $userone['id'] ;
		$user_type = $userone['user_type'] ;
		if ($user_type == 6){
			// 协会用户只返点一层 , 5%
			/**
			 * 17.7.22 协会用户不返点改
			 */
			//$rate = 5  ;
			//ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $user_invite , $userone ,"一级上家是协会用户(不判断二级上家)" , 1) ;
		}elseif ($user_type == 1 || $user_type == 2 || $user_type == 3 || $user_type == 8){
			// 1层用户返点 2%
			/**
			 * 17.7.22 一级二级用户返点改 1
			 */
			$rate = 1  ;
			ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $user_invite , $userone ,"返点给一级上家" , 1) ;
			
			if ($user_type != 8){
				// 2层用户返点 1%
				$invite2 = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$uid_one'") ;
				if (is_array($invite2))
				{
					invite_back_pay($invite2 , $pay_uid , $trade_no , $all_money , 2) ;
				}
			}
		}else{
			err_insert_rebate($pay_uid , $trade_no , $all_money , $user_invite , $userone ,"一级上家用户类型没有返点：state=".$user_type) ;
		}
	}else{
		err_insert_rebate($pay_uid , $trade_no , $all_money , $user_invite , null ,"未找到对应的上级用户") ;
	}
}
function invite_back_pay_two($invite_f , $user_invite , $pay_uid , $trade_no , $all_money)
{
	$usertwo =  sql_fetch_one("select * from `user_info` where `id` = (select `uid` from `user_invite` where `invite` = '$invite_f')") ;
	if (is_array($usertwo)){
		$user_type = $usertwo['user_type'] ;
		if ($user_type == 1 || $user_type == 2 || $user_type == 3 || $user_type == 8){
			$rate = 1  ;
			ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $user_invite , $usertwo ,"返点给二级上家" , 2) ;
		}else{
			log_save_rebate("二级上家用户类型没有返点：state=" . $user_type . get_user_string_rebate($user_invite , null) ) ;
		}
	}else{
		log_save_rebate("未找到二级上家,不产生返点." . get_user_string_rebate($user_invite , null) ) ;
	}
}


$start = 0 ;
$limit = 50 ;

log_save_rebate("开始搜索及计算返点:") ;

$coupon_type_rebate_3 = sql_fetch_one_cell("select `description` from `prf_config` where `config_attribute` = 'coupon_type_rebate_3' and `config_value` = 1 ") ;
$coupon_type_rebate_4 = sql_fetch_one_cell("select `description` from `prf_config` where `config_attribute` = 'coupon_type_rebate_4' and `config_value` = 1 ") ;

$rebate_3 = explode("|" , $coupon_type_rebate_3) ;
$rebate_3_arr = array() ;
foreach($rebate_3 as $rb)
{
    $a = explode("," , $rb) ;
    if (count($a) == 2){
        $key = intval($a[0]) ;
        $val = intval($a[1]) ;
        if ($key > 0 && $val > 0){
            $rebate_3_arr[$key] = $val ;
        }
    }
}

$rebate_4 = explode("|" , $coupon_type_rebate_4) ;
$rebate_4_arr = array() ;
foreach($rebate_4 as $rb)
{
    $a = explode("," , $rb) ;
    if (count($a) == 2){
        $key = intval($a[0]) ;
        $val = intval($a[1]) ;
        if ($key > 0 && $val > 0){
            $rebate_4_arr[$key] = $val ;
        }
    }
}

log_save_rebate("设计师全场优惠卷返点比例：" . json_encode_utf8($rebate_3_arr)) ;
log_save_rebate("装饰公司全场优惠卷返点比例：" . json_encode_utf8($rebate_4_arr)) ;

while(true){
	
	$paylist = sql_fetch_rows("select * from pay_trade where `trade_state` = 3 and unix_timestamp() - `over_time` >= 7 * 24 * 60 * 60 and `trade_no` not in (select `trade_no` from `pay_trade_rebate`) limit $start , $limit") ;
	if (is_array($paylist)) foreach($paylist as &$u){
		$pay_uid = $u['user_id'] ;		// 付款用户
		$trade_no = $u['trade_no'] ;	// 订单号
		$all_money = $u['price_modify'] ;	// 用户付款的金额

        log_save_rebate("pay_uid = $pay_uid , trade_no = $trade_no , all_money = $all_money  ") ;

        // 使用优惠卷的订单没有返点
        // 2018-3-26 , 全场优惠卷可以给赠送的用户返点

        $content = json_decode($u['content']) ;
        $coupon = get_jsonValue($content , "coupon") ;

        $coupon_user_id = 0 ;
        $coupon_id = 0 ;
        $type = 0 ; // 1 单品 , 2 套装
        $action = "" ;
        $coupon_rule = "" ;
        $price = 0 ;
        if (gettype($coupon) == "object"){
            if (gettype(get_jsonValue($coupon,"item")) == "object"){
                $js = get_jsonValue($coupon,"item") ;
                $type = 1 ;
                $coupon_user_id = get_jsonValue($js,"id") ;
                $coupon_id = get_jsonValue($js,"coupon_id") ;
                $action = get_jsonValue($js,"action") ;
                $coupon_rule = get_jsonValue($js,"coupon_rule") ;
                $price = intval(floatval(get_jsonValue($js,"price")) * 100) ;

                log_save_rebate("$type , $coupon_user_id , $coupon_id , $action , $coupon_rule , $price " ) ;
            }else
            if (gettype(get_jsonValue($coupon,"set")) == "object"){
                $js = get_jsonValue($coupon,"set") ;
                $type = 2 ;
                $coupon_user_id = get_jsonValue($js,"id") ;
                $coupon_id = get_jsonValue($js,"coupon_id") ;
                $action = get_jsonValue($js,"action") ;
                $coupon_rule = get_jsonValue($js,"coupon_rule") ;
                $price = intval(floatval(get_jsonValue($js,"price")) * 100) ;

                log_save_rebate("$type , $coupon_user_id , $coupon_id , $action , $coupon_rule , $price " ) ;
            }else
            if (gettype(get_jsonValue($coupon,"all")) == "object"){
                $js = get_jsonValue($coupon,"all") ;
                $type = 3 ;
                $coupon_user_id = get_jsonValue($js,"id") ;
                $coupon_id = get_jsonValue($js,"coupon_id") ;
                $action = get_jsonValue($js,"action") ;
                $coupon_rule = get_jsonValue($js,"coupon_rule") ;
                $price = intval(floatval(get_jsonValue($js,"price")) * 100) ;

                log_save_rebate("$type , $coupon_user_id , $coupon_id , $action , $coupon_rule , $price " ) ;
            }else{
                log_save_rebate(" coupon : all , item , set 的优惠卷才有返点" . $coupon ) ;
            }
        }
        if ($type > 0) {
            if ($action == "all" && $coupon_rule == "D")    // 全场优惠卷和折扣率配置
            {
                // todo 优惠卷要求是交易完成后15天后返点

                // 全场优惠卷给赠送的人进行返点
                $user_c = sql_fetch_one("SELECT * FROM `user_coupon` WHERE `id` = '$coupon_user_id' ");
                $fl_userid = intval($user_c['from_uid']) ;
                if ($fl_userid == 0)    $fl_userid  = $pay_uid ;

                if (is_array($user_c) && $fl_userid > 0) {
                    $user_type = sql_fetch_one_cell("select `user_type` from `user_info` where `id` = '$fl_userid' and `status` = 1");
                    if ($user_type == 3) {
                        // 认证设计师
                        $rate = 0;    // 返点比例
                        if (key_exists($price , $rebate_3_arr)){
                            $rate = $rebate_3_arr[$price] ;
                        }
                        if ($rate > 0) {
                            $user_invite = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$pay_uid'");
                            $user_fdinfo = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$fl_userid'");
                            $level = $user_fdinfo['user_type_class'];
                            ok_insert_rebate($pay_uid, $trade_no, $all_money, $rate, $user_invite, $user_fdinfo, "认证设计师转让优惠卷返利:设计师级别:$level", 0);
//                            continue;
                        } else {
                            err_insert_rebate($pay_uid, $trade_no, $all_money, null, null, "此优惠卷的没有返点利率");
//                            continue;
                        }
                    } elseif ($user_type == 4) {
                        // 装饰公司
                        $rate = 0;    // 返点比例
                        if (key_exists($price , $rebate_4_arr)){
                            $rate = $rebate_4_arr[$price] ;
                        }
                        if ($rate > 0) {
                            $user_invite = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$pay_uid'");
                            $user_fdinfo = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$fl_userid'");
                            ok_insert_rebate($pay_uid, $trade_no, $all_money, $rate, $user_invite, $user_fdinfo, "装饰公司转让优惠卷返利", 0);
//                            continue;
                        } else {
                            err_insert_rebate($pay_uid, $trade_no, $all_money, null, null, "此优惠卷的没有返点利率");
//                            continue;
                        }
                    } else {
                        err_insert_rebate($pay_uid, $trade_no, $all_money, null, null, "此优惠卷的转让者（不是装饰公司和认证设计师：user_type = $user_type ）没有返点");
//                        continue;
                    }
                } else {
                    err_insert_rebate($pay_uid, $trade_no, $all_money, null, null, "此优惠卷的订单没有返点. 转让优惠卷用户 = $fl_userid");
//                    continue;
                }
            }else{
                log_save_rebate(" coupon = all  and  coupon_rule = D 的优惠卷才有返点，此优惠卷 action = $action , coupon_rule = $coupon_rule") ;
                err_insert_rebate($pay_uid, $trade_no, $all_money, null, null, " coupon = all  and  coupon_rule = D 的优惠卷才有返点，此优惠卷 action = $action , coupon_rule = $coupon_rule");
            }
//            continue;
        }

		$user_invite = sql_fetch_one("select * from `user_invite` u inner join `user_info` t on u.uid = t.id where u.`uid`= '$pay_uid'") ;
		if (is_array($user_invite))
		{
			$invite_f = $user_invite['invite_f'] ;
			$invite_m = $user_invite['invite'] ;
			$user_state = $user_invite['user_type'] ;					// 用户类型
			$user_type_class = $user_invite['user_type_class'] ;		// 用户级别 ，付费用户 = 5
			// 如果是认证设计师,先给自己返点.
			/**
			 * （设计师不返点 17.7.22 修改）
			 
			if ($user_state == 3 && $user_type_class != 5 && $invite_m != "888888")
			{
				$rate = 0 ;	// 返点比例
				$level = $user_invite['user_type_class'] ; 
				if ($level == 1){
					$rate = 10 ;
				}
				if ($rate > 0){
					ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $user_invite , $user_invite ,"认证设计师给自己返点:设计师级别:$level" , 0) ;
				}
			}
			*/
			/**
			 * （只给注册用户返点 17.7.22 修改）
			 */
			// 18.2.26 取消 -- 注册用户10%的购买返点取消
//			if (($user_state == 1 || $user_state == 2) && $invite_m != "888888"){
//				$rate = 10 ;
//				ok_insert_rebate($pay_uid , $trade_no , $all_money , $rate , $user_invite , $user_invite ,"注册用户给自己返点" , 0) ;
//			}
			invite_back_pay($user_invite , $pay_uid , $trade_no , $all_money , 1) ;			
		}else{
			err_insert_rebate($pay_uid , $trade_no , $all_money , null , null ,"没有找到付款用户对应的邀请码") ;
		}
	}else{
		break ;
	}
	if (count($paylist) != $limit){
		break ;
	}	
	 
}



$start = 0 ;
$limit = 50 ;

log_save_rebate("开始删除二个月未付款的订单:") ;

while(true) {
    $check_time = 2 * 30 * 24 * 60 * 60 ;
    $paylist = sql_fetch_rows("select * from pay_trade where `price_state` = 0 and `create_time` + $check_time <= unix_timestamp() limit $start , $limit");
    if (is_array($paylist)) foreach ($paylist as &$u) {
        $id = $u['id'] ;
        $trade_no = $u['trade_no'] ;	// 订单号

        $isdel = intval(sql_fetch_one_cell("select `id` from pay_trade_del where `id` = '$id'")) ;
        if ($isdel > 0){
            // 以前已经删除过
            sql_query("delete from pay_trade where `id` = '$id'");
            log_save_rebate("订单已经存在删除表了,删除源表数据 : $id -- $trade_no");
        }else {
            sql_query("insert into pay_trade_del select * from pay_trade where `id` = '$id'") ;

            if (intval(sql_fetch_one_cell("select `id` from pay_trade_del where `id` = '$id'")) > 0){
                sql_query("delete from pay_trade where `id` = '$id'");
                log_save_rebate("订单删除成功(移动到表 pay_trade_del 中) : $id -- $trade_no");
            } else {
                log_save_rebate("订单删除失败 : $id -- $trade_no");
            }
        }
    }else{
        break ;
    }
    if (count($paylist) != $limit){
        break ;
    }
}

?>